﻿using System;
using System.Messaging;

namespace TSites.Utility
{
	public class MSMQSender<T> : LoggerBase
	{
		private string _msmqQueuePath = null;
		private IMessageFormatter _msgFormatter = null;

		public MSMQSender(string msmqPath, IMessageFormatter formatter)
		{
			_msmqQueuePath = msmqPath;
			_msgFormatter = formatter;
		}

		public void QueueMessage(T Tobject)
		{
			if (Tobject != null)
			{
				Message msmqMsg = null;
				MessageQueue msmqQueue = null;
				try
				{
					msmqMsg = new Message(Tobject, _msgFormatter);
					msmqMsg.Recoverable = true;

					//If the Message queue does not exists at specified location create it
					if (MessageQueue.Exists(_msmqQueuePath))
					{
						// creates an instance MessageQueue, which points 
						// to the already existing MyQueue
						msmqQueue = new MessageQueue(_msmqQueuePath);
					}
					else
					{
						// creates a new private queue
						msmqQueue = MessageQueue.Create(_msmqQueuePath);
					}
					msmqQueue.Formatter = _msgFormatter;
					msmqQueue.Send(msmqMsg);
				}
				catch (Exception ex)
				{
					Error(ex.Message, ex);
				}
				
				// close queue
				if (msmqQueue != null)
				{
					msmqQueue.Close();
				}
			}
		}

		protected override Type LogPrefix
		{
			get { return typeof(T); }
		}
	}
}